package ch.fusun.baron.map.ui.gef.editpart;

import java.util.LinkedList;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;

import ch.fusun.baron.core.injection.ReInjector;
import ch.fusun.baron.map.Tile;

/**
 * Handles the registration of tile extensions
 */
public class TileExtensionUtil {

	private static final String TILE_EXTENSION_ID = "ch.fusun.baron.map.ui.tilextension"; //$NON-NLS-1$
	private static final String PROVIDER = "provider"; //$NON-NLS-1$
	private static TileExtensionUtil instance;
	private final List<TileChildrenProvider> providers = new LinkedList<TileChildrenProvider>();

	/**
	 * Constructor
	 * 
	 */
	public TileExtensionUtil() {
		IConfigurationElement[] config = Platform.getExtensionRegistry()
				.getConfigurationElementsFor(TILE_EXTENSION_ID);
		try {
			for (IConfigurationElement e : config) {
				TileChildrenProvider bean = (TileChildrenProvider) e
						.createExecutableExtension(PROVIDER);
				providers.add(bean);
				ReInjector.getInstance().reInject(bean);
			}
		} catch (CoreException ex) {
			System.err.println("Handle this error with log or so: " //$NON-NLS-1$
					+ ex.getMessage());
		}
	}

	/**
	 * @return The singleton instance
	 */
	public static TileExtensionUtil getInstance() {
		if (instance == null) {
			instance = new TileExtensionUtil();
		}
		return instance;
	}

	/**
	 * @param model
	 *            the tile model
	 * @return all tile children
	 */
	@SuppressWarnings("rawtypes")
	public List<TileChild> getChildren(Tile model) {
		List<TileChild> children = new LinkedList<TileChild>();
		for (TileChildrenProvider provider : providers) {
			children.addAll(provider.getChildren(model));
		}
		return children;
	}

	/**
	 * @return the tile children providers
	 */
	public List<TileChildrenProvider> getProviders() {
		return providers;
	}
}
